<template>
  <div class="panel-tab__content">
    <el-table :data="elementPropertyList"  max-height="240" border fit>
      <el-table-column label="序号" width="50px" type="index" />
      <el-table-column label="属性名" prop="name" min-width="100px" show-overflow-tooltip />
      <el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />
      <el-table-column label="操作" width="90px">
        <template #default="{ row, $index }">
          <el-button size="small" type="text" @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="small" type="text" style="color: #ff4d4f" @click="removeAttributes(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="element-drawer__button">
      <el-button size="small" type="primary" icon="Plus" @click="openAttributesForm(null, -1)">添加属性</el-button>
    </div>

    <el-dialog v-model="propertyFormModelVisible" title="属性配置" width="600px" append-to-body destroy-on-close>
      <el-form :model="propertyForm" label-width="80px" size="small" ref="attributeFormRef" @submit.native.prevent>
        <el-form-item label="属性名：" prop="name">
          <el-input v-model="propertyForm.name" clearable />
        </el-form-item>
        <el-form-item label="属性值：" prop="value">
          <el-input v-model="propertyForm.value" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="propertyFormModelVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveAttribute">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ElementProperties">
const {proxy} = getCurrentInstance()

const props = defineProps({
  id: String,
  type: String
})
const {id,type} = toRefs(props)
const prefix = inject('prefix')
const width = inject('width')
const state = reactive({
  elementPropertyList: [],
  propertyForm: {},
  editingPropertyIndex: -1,
  propertyFormModelVisible: false,
  bpmnElement: undefined,
  otherExtensionList: [],
  bpmnElementPropertyList: []
})
const {elementPropertyList,propertyForm,editingPropertyIndex,propertyFormModelVisible} = toRefs(state)

watch(()=>props.id,(val) => {
  val && val.length && resetAttributesList();
}, { immediate: true })

function resetAttributesList() {
  state.bpmnElement = window.bpmnInstances.bpmnElement;
  state.otherExtensionList = []; // 其他扩展配置
  let bpmnElementProperties =
  state.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
      if (ex.$type !== `${prefix}:Properties`) {
        state.otherExtensionList.push(ex);
      }
      return ex.$type === `${prefix}:Properties`;
    }) ?? [];

  // 保存所有的 扩展属性字段
  state.bpmnElementPropertyList = bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), []);
  // 复制 显示
  state.elementPropertyList = JSON.parse(JSON.stringify(state.bpmnElementPropertyList ?? []));
}
function openAttributesForm(attr, index) {
  state.editingPropertyIndex = index;
  state.propertyForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
  state.propertyFormModelVisible = true;
  proxy.$nextTick(() => {
    if (proxy.$refs["attributeFormRef"]) proxy.$refs["attributeFormRef"].clearValidate();
  });
}
function removeAttributes(attr, index) {
  proxy.$confirm("确认移除该属性吗？", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消"
  })
    .then(() => {
      state.elementPropertyList.splice(index, 1);
      state.bpmnElementPropertyList.splice(index, 1);
      // 新建一个属性字段的保存列表
      const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
        values: state.bpmnElementPropertyList
      });
      updateElementExtensions(propertiesObject);
      resetAttributesList();
    })
    .catch(() => console.info("操作取消"));
}
function saveAttribute() {
  const { name, value } = state.propertyForm;
  if (state.editingPropertyIndex !== -1) {
    window.bpmnInstances.modeling.updateModdleProperties(toRaw(state.bpmnElement), state.bpmnElementPropertyList[state.editingPropertyIndex], {
      name,
      value
    });
  } else {
    // 新建属性字段
    const newPropertyObject = window.bpmnInstances.moddle.create(`${prefix}:Property`, { name, value });
    // 新建一个属性字段的保存列表
    const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
      values: state.bpmnElementPropertyList.concat([newPropertyObject])
    });
    updateElementExtensions(propertiesObject);
  }
  state.propertyFormModelVisible = false;
  resetAttributesList();
}
function updateElementExtensions(properties) {
  const extensions = window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
    values: state.otherExtensionList.concat([properties])
  });
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), {
    extensionElements: extensions
  });
}

</script>
